import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {AccountsService} from "./accounts.service";
import {ResponseUtil} from "../../../util/response-util";
import {Account} from "./account";
import {MsgResult} from "../../../models/msg-result";
import {Page, Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {API, MsgConstants} from "../../../constants/constants";
import {TableUtil} from "../../../util/table-util";

declare var $;

@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html'
})
export class AccountsComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  //声明实例对象
  accounts: Account[];

  id: string;

  accountIds :Array<string> =[];

  table;
  clickRowData;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private accountsService: AccountsService,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService
  ) { }


  proxy = {
    "accountAdd": () => this.accountAdd(),
    "accountUpdate": () => this.accountUpdate(),
    "accountDelete": () => this.accountDelete(),
    //修改密码
    "updatePassword": () => this.updatePassword(),
    //密码重置
    "passwordReset": () => this.passwordReset(),
    //分配角色
    "accountAssignRole": () => this.accountAssignRole(),
    //分配权限
    "accountAssignAuthority": () => this.accountAssignAuthority(),
    //设置主题
    "accountSetThemes":() => this.accountSetThemes(),
    //设置门户
    "accountSetProtals":() => this.accountSetPortals(),
    //设置首页
    "accountSetMenu":() => this.accountSetMenu()
  }


  ngOnInit() {
    //初始化表单...
    this.loadAccount();
    this.pushPage();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("账户管理", "查询", path);
  }


  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 账户列表查询   one_table_account
   */
  loadAccount() {
    this.table = this.tableUtil.load("one_table_account",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "accountName", title: '名称', align: 'left'},
        {field: "themeName", title: '主题', align: 'left'},
        {field: "portalName", title: '门户', align: 'left'},
        {field: "isAudit", title: '审核',class:"one-table-col-2", align: 'middle', formatter: this.yesOrNoFormat},
        {field: "isEnable", title: '启用',class:"one-table-col-2", align: 'middle', formatter: this.yesOrNoFormat},
        {field: "isAllowPc", title: 'PC端登录',class:"one-table-col-6", align: 'middle', formatter: this.yesOrNoFormat},
        {field: "isAllowApp", title: '移动端登录',class:"one-table-col-6", align: 'middle', formatter: this.yesOrNoFormat},
        {field: "isUse", title: '使用',class:"one-table-col-2", align: 'left', formatter: this.yesOrNoFormatText},
        {field: "creatorName", title: '创建人', align: 'left', visible: false},
        {field: "CREATE_DATE", title: '创建日期', align: 'left', sortName: "CREATE_DATE", sortable: true, visible: false},
        {field: "editorName", title: '修改人', align: 'left',visible: false},
        {field: "MODIFIED_DATE", title: '修改日期', align: 'left', sortName: "MODIFIED_DATE", sortable: true, visible:false}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_accounts",
      url: API.accountPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.accountName = $("#accountName").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.CREATE_DATE = value.createDate || '';
            value.MODIFIED_DATE = value.modifiedDate || '';
          });
        });
      },
      onClickCell:(field, value, row, $element) =>{
        if(field=="isEnable"|| field=="isAudit"|| field=="isAllowPc"|| field=="isAllowApp"){
          let rowData = row;
          if(value=="0"){
            rowData[field] = "1";
          }else if(value=="1"){
            rowData[field] = "0";
          }
          this.postAccountSpeedInfo(field, rowData[field],rowData.id);
          this.clickRowData = rowData;
        }else{
          return false;
        }
      },
      height: 700,//table高度
      sortable: true,
      order: 'asc',
      sortName: 'MODIFIED_DATE',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true ,//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return '<input type="checkbox" checked>';
    }
    if (value == '0') {
      return '<input type= "checkbox">';
    }
  }
  private yesOrNoFormatText(value, row, index) {
    if (value == '1') {
      return '是';
    }
    if (value == '0') {
      return '否';
    }
  }

  /**
   * 添加账户
   */
  accountAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  /**
   * 批量删除
   */
  accountDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length == 0) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }


  /**
   * 实现批量删除操作
   * 1.判断id字符串是否存在
   * 2.调取后端删除操作；
   */
  private requestDelete = () => {
    //调用后端接口
    if (!!this.accountIds) {
      this.accountsService.deleteAcounts(this.accountIds).subscribe(
        result => this.responseUtil.success(result, this.processDeleteResult),
        error => this.responseUtil.error(error)
      );
    }else{
      this.dialogService.modalInfo("请选择一条数据");
    }
  }

  /**
   * 处理删除结果
   * 1.判断是否删除成功；
   * @param result
   */
  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 修改账户信息
   */
  accountUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    if(!rows[0]){
      return this.dialogService.modalInfo("请选择一条数据!");
    }
    this.id = this.tableUtil.getId(rows[0]);
    if (!this.id) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['update', {accountId: this.id}], {relativeTo: this.route});
    }
  }

  /**
   * 修改密码
   */
  updatePassword() {
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['pwd', {accountId: this.accountIds[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 密码重置
   */
  passwordReset() {
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确认重置密码？", () => this.requestPasswordReset(this.accountIds[0]),() => this.search());
    }
  }

  /**
   * 确认密码重置
   */
  private requestPasswordReset =(id)=> {
    //调用后端接口
    if (!!id) {
      this.accountsService.resetPwd(id).subscribe(
        result => this.responseUtil.success(result, this.processPwdResResult),
        error => this.responseUtil.error(error)
      );
    }
  }

  private processPwdResResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success("密码重置成功！");
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 为账户分配角色
   */
  accountAssignRole() {
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['assi', {accountId: this.accountIds[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 分配权限
   */
  accountAssignAuthority() {
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['authority', {accountId: this.accountIds[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 快捷操作提交
   */
  postAccountSpeedInfo(flag,value,id){
    this.accountsService.postAccountSpeedySet(flag,value,id).subscribe(
      result => this.responseUtil.success(result, this.processSpeedResult),
      error => this.responseUtil.error(error)
    )
  }
  private processSpeedResult= (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.table.bootstrapTable("updateRow",this.clickRowData);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  /**
   * 添加主题
   */
  accountSetThemes(){
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length == 0) {
      this.dialogService.modalInfo("请选择一条或多条数据");
    }else {
      this.router.navigate(['themes',{accountId: this.accountIds.join(",")}], {relativeTo: this.route});
    }
  }
  /**
   * 添加门户
   */
  accountSetPortals(){
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length == 0) {
      this.dialogService.modalInfo("请选择一条或多条数据");
    }else {
      this.router.navigate(['portals',{accountId: this.accountIds.join(",")}], {relativeTo: this.route});
    }
  }

  /**
   * 批量设置首页
   */
  accountSetMenu(){
    let rows = this.table.bootstrapTable('getSelections');
    this.accountIds = this.tableUtil.getIds(rows);
    if (this.accountIds.length == 0) {
      this.dialogService.modalInfo("请选择一条或多条数据");
    }else {
      this.router.navigate(['menu',{accountId: this.accountIds.join(",")}], {relativeTo: this.route});
    }
  }

}
